package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.IngredientForm;
import ru.housewife.form.IngredientGroupForm;
import ru.housewife.form.WareForm;
import ru.housewife.form.WaresGroupForm;
import ru.housewife.model.Ingredient;
import ru.housewife.model.Ware;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author atroshanin
 */
public class GetAllIngredients implements HibernateAction<List<IngredientForm>>{

    private CacheManager cacheManager;

    public GetAllIngredients(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public List<IngredientForm> execute(Session session) {
        Query q = session.createQuery("select i from Ingredient i");

        List<Ingredient> lst = q.list();
        List<IngredientForm> result = new ArrayList<IngredientForm>(lst.size());
        for (Ingredient ingredient : lst) {
            IngredientGroupForm group = cacheManager.getIngredientGroupForm(ingredient.getIngredientGroup().getId());
            result.add(createWareForm(ingredient, group));
        }
        return result;
    }

    private IngredientForm createWareForm(Ingredient ingredient, IngredientGroupForm group) {
        IngredientForm frm = new IngredientForm(ingredient);
        frm.setIngredientGroup(group);
        group.addIngredient(frm);
        return frm;
    }

}
